//
//  ViewController.m
//  Lazy
//
//  Created by Echo on 14-4-1.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "ViewController.h"
#import "GoodBtn.h"
#import "GoodLabel.h"
#import "StudyingViewController.h"
#import "WsHUD.h"
#import "RecInfo.h"
#import "singlePeripheral.h"

NSString * const Characteristic_HeartRateControlPoint_UUID = @"FFF1";

@interface ViewController (){
//    CBCentralManager    *centeralManager;
    NSMutableArray *peripherals;
    BOOL pendingInit;
}
//@property (strong, nonatomic) CBPeripheral          *discoveredPeripheral;
@property (strong, nonatomic) CBCharacteristic      *discoveredCBCharacteristic;
@property (strong, nonatomic) CBCharacteristic      *readCBCharacteristic;
@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        peripherals = [[NSMutableArray alloc] init];
        timeArray = [[NSMutableArray alloc] init];
        curArray = [[NSMutableArray alloc] init];
        savaArray = [[NSMutableArray alloc] init];
        pendingInit = YES;
        isConnect = NO;
        [singlePeripheral instance].centeralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
    }
    return self;
    
    if (pendingInit) {
        NSLog(@"Discover is pending Init");
        return [NSError errorWithDomain:@"Discover is pending Init" code:-1 userInfo:nil];
    }
}
-(void)setDefaultMode{
    NSString *strModel = [[NSUserDefaults standardUserDefaults] objectForKey:@"model"];
    NSString *strEar = [[NSUserDefaults standardUserDefaults] objectForKey:@"ear"];
    NSString *strLevel = [[NSUserDefaults standardUserDefaults] objectForKey:@"level"];
    if (!strModel) {
        [[NSUserDefaults standardUserDefaults] setObject:@"01" forKey:@"model"];
    }
    if (!strEar) {
        [[NSUserDefaults standardUserDefaults] setObject:@"00" forKey:@"ear"];
    }
    if (!strLevel) {
        [[NSUserDefaults standardUserDefaults] setObject:@"00" forKey:@"level"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)startScan
{
    if (!isConnect) {
        
        NSLog(@"startScan");
        if (timer) {
            [timer invalidate]; timer = nil;
        }
        [WsHUD showHUDWithLabel:STR(@"正在搜寻设备...") modal:YES timeoutDuration:0];
        
        //check if serviceUUIDS contain NSString
        NSString *serviceID = Heart_Rate_Service;
        NSMutableArray *services = [[NSMutableArray alloc]init];
        CBUUID *serUUID = [CBUUID UUIDWithString:serviceID];
        [services addObject:serUUID];
        
        [[singlePeripheral instance].centeralManager retrieveConnectedPeripherals];
        [[singlePeripheral instance].centeralManager scanForPeripheralsWithServices:services options:nil];
//        [[singlePeripheral instance].centeralManager scanForPeripheralsWithServices:nil options:nil];
//        
        isConnect = YES;
    }
}
- (BOOL)supportLEHardware
{
    NSString * state = nil;
    BOOL is_support = YES;
    switch ([[singlePeripheral instance].centeralManager state])
    {
        case CBCentralManagerStateUnsupported:
            is_support = NO;
            state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
            break;
        case CBCentralManagerStateUnauthorized:
            state = @"The app is not authorized to use Bluetooth Low Energy.";
            break;
        case CBCentralManagerStatePoweredOff:
            state = @"Bluetooth is currently powered off.";
            break;
        case CBCentralManagerStatePoweredOn:
            return TRUE;
        case CBCentralManagerStateUnknown:
        default:
            return false;
    }
    NSLog(@"Central manager state: %@", state);
    if (is_support == NO) {
        UIAlertView *alvert = [[UIAlertView alloc] initWithTitle:STR(@"提示") message:STR(@"此手机不支持蓝牙4.0") delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alvert show];
    }
    return false;
}
/** Once the disconnection happens, we need to clean up our local copy of the peripheral
 */
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    [singlePeripheral instance].discoveredPeripheral = nil;
    isConnect = NO;
    // We're disconnected, so start scanning again
   [self startScan];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (![self supportLEHardware])
    {
//        @throw ([NSError errorWithDomain:@"Bluetooth LE not supported"
//                                    code:999
//                                userInfo:nil]);
    }
    if (central.state != CBCentralManagerStatePoweredOn) {
        // In a real app, you'd deal with all the states correctly
        return;
    }
    // The state must be CBCentralManagerStatePoweredOn...
    // ... so start scanning
    [self startScan];
    
    return;
    
    NSError *error = nil;
    switch ([singlePeripheral instance].centeralManager.state) {
        case CBCentralManagerStatePoweredOn:
        {
            pendingInit = NO;
        }
            break;
        case CBCentralManagerStatePoweredOff:
        {
            error = [NSError errorWithDomain:@"CBCentralManagerStatePoweredOff" code:-1 userInfo:nil];
        }
            break;
        case CBCentralManagerStateResetting:
        {
            pendingInit = YES;
        }
            break;
        case CBCentralManagerStateUnknown:
        {
            error = [NSError errorWithDomain:@"CBCentralManagerStateUnknown" code:-1 userInfo:nil];
        }
            break;
        case CBCentralManagerStateUnsupported:
        {
            error = [NSError errorWithDomain:@"CBCentralManagerStateUnsupported" code:-1 userInfo:nil];
        }
            break;
        default:
            break;
    }
    NSLog(@"error : %@", error);
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);
    NSLog(@"advertisementData %@", advertisementData);
    if ([singlePeripheral instance].discoveredPeripheral != peripheral) {
        [[singlePeripheral instance].centeralManager stopScan];
        [singlePeripheral instance].discoveredPeripheral = peripheral;
        // And connect
        NSLog(@"Connecting to peripheral %@", peripheral);
        [[singlePeripheral instance].centeralManager connectPeripheral:peripheral options:nil];
    }
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Peripheral Connected");
    peripheral.delegate = self;//因为在后面我们要从外设蓝牙那边再获取一些信息，并与之通讯，这些过程会有一些事件可能要处理，所以要给这个外设设置代理，比如：
    // Search only for services that match our UUID
    [peripheral discoverServices:nil];//查询所有蓝牙服务
}
//返回的蓝牙服务通知通过代理实现
- (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error {
    NSLog(@"didDiscoverServices:\n");
    if (error) {
        NSLog(@"Discovered services for %@ with error: %@", aPeripheral.name, [error localizedDescription]);
        return;
    }
    if (!error) {
        NSLog(@"====%@\n", aPeripheral.name);
        for (CBService *service in aPeripheral.services){
            NSLog(@"Service found with UUID: %@(%@)\n", service.UUID.data,service.UUID);
//            NSLog(@"discoverCharacteristics for service: %@", service.UUID.UUIDString);／／ios5崩溃
            [aPeripheral discoverCharacteristics:nil forService:service];
        }
    }
    else {
        NSLog(@"Service discovery was unsuccessfull !\n");
    }
}
//在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    isConnect = YES;
    if (error){
        NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    // Again, we loop through the array, just in case.
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"characteristic : %@", characteristic.UUID);
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {//往FFF1发送数据
            self.discoveredCBCharacteristic = characteristic;
            [WsHUD findAndHideHUD:NO];
        }
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]) {
            self.readCBCharacteristic = characteristic;
        }
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
}
//3处理蓝牙发过来的数据
//在这个方法中我们要找到我们所需的服务的特性 然后调用setNotifyValue方法告知我们要监测这个服务特性的状态变化
- (void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
        NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
        NSLog(@"characteristic.UUID (%@) Received:  %@", [characteristic.UUID UUIDString], stringFromData);
    char* pRecv1 = (char*)[characteristic.value bytes];
    if (pRecv1) {
        for (int i=0; i<[characteristic.value length]; i++) {
            NSLog(@"recvxxx:[%d]:0x%02x %c", i, pRecv1[i], pRecv1[i]);
        }
    }
}
//3.7给蓝牙发数据
//这时还会触发一个代理事件
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
//    if (error) {
//        NSLog(@"=======%@",error.userInfo);
//    }else{
//        NSLog(@"发送数据成功");
//    }
//    NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
//    NSLog(@"Receivedd xxxx : %@", stringFromData);
//    char* pRecv1 = (char*)[characteristic.value bytes];
//    if (pRecv1) {
//        for (int i=0; i<[characteristic.value length]; i++) {
//            NSLog(@"recvxxx:[%d]:0x%02x %c", i, pRecv1[i], pRecv1[i]);
//        }
//    }
}
NSData * dataWithString(NSString *sendString) {
    sendString = [sendString uppercaseString];
    if ([sendString length] % 2 == 0) {
        int bitCount = (int)[sendString length];
        NSMutableData *sendData = [NSMutableData data];
        for (int i = 0; i < bitCount; i+= 2) {
            NSString *subString = [sendString substringWithRange:NSMakeRange(i, 2)];
            //字母处理 判断是否有 字母
            BOOL withChar = NO;
            int bufferWithChar = 0;
            for (int r = 0; r < 2; r++) {
                NSString *tempString = [subString substringWithRange:NSMakeRange(r, 1)];
                NSData *data = [tempString dataUsingEncoding:NSASCIIStringEncoding];
                char tempBuffer = 0;
                [data getBytes:&tempBuffer];
                if (tempBuffer < 65) {
                    bufferWithChar += (r==0?16:1) * (tempBuffer - 48);
                }
                if (tempBuffer >= 65) {
                    withChar = YES;
                    bufferWithChar += (r==0?16:1) * (tempBuffer - 55);
                }
            }
            char buffer = 0;
            if (withChar) {
                buffer = bufferWithChar;
            } else {
                buffer = [subString intValue];
                int temp = 6 * (buffer / 10);
                buffer += temp;
            }
            [sendData appendBytes:&buffer length:1];
        }
        //        NSLog(@"sendData %@",sendData);
        return sendData;
    }
    return nil;
}
//@"C0FF02FF01FF00FF03FFC0"关机
-(void)sendDataToBluetooth:(NSString*)str{
//    str = @"32434509300e0a1e0100005533";
    str = [NSString stringWithFormat:@"324345%@%@%@5533", @"0930", @"0e0a12", @"010000"];
    NSLog(@"str %@", str);
    if (!self.discoveredCBCharacteristic) {
        NSLog(@"cannot send data");
        return;
    }
//    if ([str length]  != 22) {
//        NSLog(@"数据长度不对");
//    }
    
//    unsigned char test[1024] = {'\0'};
//    test[0] = 0x55;//前导码
//    test[1] = 0x04;//上行 类型
//    test[2] = 0x01;//模式
//    test[3] = 0x01;//位置
//    test[4] = 0x01;//强度
//    test[5] = 0x05;//结束码
//    NSMutableData *crcdata = [NSMutableData data];
//    [crcdata appendBytes:test length:6];
//    
//    char* pRecv = (char*)[crcdata bytes];
//    if (pRecv) {
//        for (int i=0; i<[crcdata length]; i++) {
//            NSLog(@"send[%d]:0x%02x %c", i, pRecv[i], pRecv[i]);
//        }
//    }
    NSLog(@"senddata %@", str);
    [[singlePeripheral instance].discoveredPeripheral writeValue:dataWithString(str) forCharacteristic:self.discoveredCBCharacteristic type:CBCharacteristicWriteWithResponse];
}
-(void)readBluetoothData:(NSString*)str{
    str = [NSString stringWithFormat:@"324345%@5533", @"bb"];
    if (!self.readCBCharacteristic) {
        NSLog(@"cannot read data");
        return;
    }
    NSLog(@"read data %@", str);
    [[singlePeripheral instance].discoveredPeripheral readValueForCharacteristic:self.readCBCharacteristic];
}
-(void)initCureSettingView{
    leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44-FH(bottomView))];
    leftView.backgroundColor = RGB(246, 246, 246, 1);
    [self.view addSubview:leftView];
    
    for (int i=0; i<3; i++) {
        GoodLabel *label = [GoodLabel labelWithFont:15 title:STR(@"强度设置")];
        label.textColor = [UIColor blackColor];
        if (i == 1) {
            label.text = STR(@"模式设置");
        }else if (i == 2) {
            label.text = STR(@"治疗部位设置");
        }
        label.frame = CGRectMake(20, 10+i*50, SCREEN_WIDTH, 50);
        [leftView addSubview:label];
        
        UIImageView *line = [[UIImageView alloc] initWithImage:[IMG(@"line.png") stretchableImageWithLeftCapWidth:1 topCapHeight:0]];
        line.frame = CGRectMake(0, FY(label)+FH(label), SCREEN_WIDTH, 1);
        [leftView addSubview:line];
        
        GoodBtn *btn = [GoodBtn buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        [btn addTarget:self action:@selector(selectPressed:) forControlEvents:UIControlEventTouchUpInside];
        [btn setBackgroundImage:IMG(@"btn_triangle.png") forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor redColor];
        btn.frame = CGRectMake(SCREEN_WIDTH-60, 10+i*50+4, 92/2, 87/2);
        [leftView addSubview:btn];
    }
    
    GoodBtn *btn = [GoodBtn buttonWithType:UIButtonTypeCustom];
//    btn.hidden = YES;
    [btn setTitleColor:RGB(137, 137, 137, 1) forState:UIControlStateNormal];
    [btn setBackgroundImage:IMG(@"y1.png") forState:UIControlStateNormal];
    btn.titleEdgeInsets = UIEdgeInsetsMake(30, 0, 10, 0);
    [btn setTitle:STR(@"开始") forState:UIControlStateNormal];
    btn.frame = CGRectMake((SCREEN_WIDTH-272/2)/2+2, FH(leftView)-150-20, 272/2, 261/2);
    [btn addTarget:self action:@selector(studyPressed:) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:btn];
    
}
-(void)bgviewPressed:(UIButton*)btn{
    [bgview removeFromSuperview]; bgview = nil;
}
-(void)initBgView{
    bgview = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgview.backgroundColor = RGB(0, 0, 0, .4);
    [bgview addTarget:self action:@selector(bgviewPressed:) forControlEvents:UIControlEventTouchUpInside];
    [[self keyWindow] addSubview:bgview];
}
-(void)selectPressed:(UIButton*)btn{
}

-(void)defalutSetPressed{
    NSString *strModel = [[NSUserDefaults standardUserDefaults] objectForKey:@"modelDefault"];//00
    NSString *strEar = [[NSUserDefaults standardUserDefaults] objectForKey:@"earDefault"];//00
    NSString *strLevel = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelDefault"];//01
    
    NSString *string = nil;
    if (strModel && strEar && strLevel) {
        if ([strModel isEqualToString:@"05"]) {
            string = [NSString stringWithFormat:@"C0FF03FF%@FF%@FF%@FFC0", @"00", strEar, strLevel];
        }else{
            string = [NSString stringWithFormat:@"C0FF03FF%@FF%@FF%@FFC0", strModel, strEar, strLevel];
        }
    }
    [self sendDataToBluetooth:string];
}
-(void)studyPressed:(UIButton*)btn{
    
    NSString *strModel = [[NSUserDefaults standardUserDefaults] objectForKey:@"model"];
    NSString *strEar = [[NSUserDefaults standardUserDefaults] objectForKey:@"ear"];
    NSString *strLevel = [[NSUserDefaults standardUserDefaults] objectForKey:@"level"];
    
    if ([strModel length] > 0 && [strEar length] > 0 && [strLevel length] > 0) {
        if ([strModel isEqualToString:@"05"]) {
            [self sendDataToBluetooth:[NSString stringWithFormat:@"C0FF03FF%@FF%@FF%@FFC0",@"00", strEar, strLevel]];
        }else{
            [self sendDataToBluetooth:[NSString stringWithFormat:@"C0FF03FF%@FF%@FF%@FFC0",strModel, strEar, strLevel]];
        }
    }else{
        [self sendDataToBluetooth:@"C0FF03FF01FF00FF03FFC0"];//启动治疗
    }
    
    StudyingViewController *viewController = [[StudyingViewController alloc] init];
    [viewController setModel:strModel];
    [viewController setLevel:strLevel];
    [viewController setPosition:strEar];
    [self.navigationController pushViewController:viewController animated:YES];
}
-(void)initLeftMidView{
    
    leftMidView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44-FH(bottomView))];
    leftMidView.hidden = YES;
    [self.view addSubview:leftMidView];
    
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44-FH(bottomView))];
    downView.backgroundColor = [UIColor whiteColor];
    downView.tag = 100;
    [leftMidView addSubview:downView];
    
    
    GoodBtn *btn = [GoodBtn buttonWithType:UIButtonTypeCustom];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:IMG(@"y1.png") forState:UIControlStateNormal];
    btn.titleEdgeInsets = UIEdgeInsetsMake(30, 0, 10, 0);
    [btn setTitle:STR(@"确认") forState:UIControlStateNormal];
    btn.frame = CGRectMake((SCREEN_WIDTH-272/2)/2+2, FH(leftView)-150-20, 272/2, 261/2);
    [btn addTarget:self action:@selector(addDrugPressed) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:btn];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)btnDrugSelect{
    TableView4.hidden = !TableView4.hidden;
}
-(void)btnSwitchPressed{
    isSelectDrug = !isSelectDrug;
    if (isSelectDrug) {
        [self selectDateWithKey:REC_DRUG_INFO];
    }else{
        [self selectDateWithKey:RECINFO];
    }
}
-(void)addDrugPressed{
    
}
-(void)initMidView{
    
    midView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44-FH(bottomView))];
    midView.backgroundColor = leftView.backgroundColor;
    [self.view addSubview:midView];
    
   
}
-(void)btnSelect{
    TableView2.hidden = !TableView2.hidden;
}
-(UIWindow*)keyWindow{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    if (!keyWindow) {
        keyWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    return keyWindow;
}
-(void)initDefaultView{
    
    rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20-44-FH(bottomView))];
    rightView.backgroundColor = leftView.backgroundColor;
    [self.view addSubview:rightView];
    
    
    GoodBtn *btn = [GoodBtn buttonWithType:UIButtonTypeSystem];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:IMG(@"navi_bar.png") forState:UIControlStateNormal];
    [btn setTitle:STR(@"启用默认设置") forState:UIControlStateNormal];
    btn.frame = CGRectMake(20, FH(leftView)-130, SCREEN_WIDTH-20*2, 40);
    [btn addTarget:self action:@selector(defalutSetPressed) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:btn];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
//关机
-(void)off_left{
    [self sendDataToBluetooth:@"C0FF02FF01FF00FF03FFC0"];//关机
}
//开机
-(void)on_right{
    [self sendDataToBluetooth:@"C0FF01FF01FF00FF03FFC0"];//开机
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    return;
    
    [self setDefaultMode];
    
    self.title = STR(@"治疗设置");
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:STR(@"关机") style:UIBarButtonItemStylePlain target:self action:@selector(off_left)];
//     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:STR(@"开机") style:UIBarButtonItemStylePlain target:self action:@selector(on_right)];

    self.view.backgroundColor = [UIColor whiteColor];
    
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight-20-44-bottomview_height, kScreenWidth, bottomview_height)];
    bottomView.backgroundColor = RGB(248, 248, 248, 1);
    [self.view addSubview:bottomView];
    
    [self initCureSettingView];
    
    [self initMidView];
    [self initLeftMidView];
    
    [self initDefaultView];
    
    midView.hidden = YES;
    rightView.hidden = YES;
    
    float count = 4.0;
    
    for (int i=0; i<count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.adjustsImageWhenHighlighted = NO;
        btn.frame = CGRectMake(i*(kScreenWidth/count), 0, kScreenWidth/count, FH(bottomView));
        GoodLabel *descLabel = [GoodLabel labelWithFont:11 title:STR(@"治疗设置")];
        descLabel.textColor = [UIColor blackColor];
        descLabel.textAlignment = NSTextAlignmentCenter;
        descLabel.frame = CGRectMake(0, 30, btn.frame.size.width, 16);
        [btn addSubview:descLabel];
        btn.imageEdgeInsets = UIEdgeInsetsMake(2,  0,  FH(btn)-30-2, 0);
        if (i == 0) {
            btn.enabled = NO;
            btn1 = btn;
            [btn setImage:IMG(@"setting_bottom.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"setting_bottom_un.png") forState:UIControlStateDisabled];
        }else if (i == 1) {
            descLabel.text = STR(@"添加药物");
            btn12 = btn;
            [btn setImage:IMG(@"add_un.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"add.png") forState:UIControlStateDisabled];
        }else if (i == 2) {
            descLabel.text = STR(@"记录查询");
            btn2 = btn;
            [btn setImage:IMG(@"edit_bottom.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"edit_bottom_un.png") forState:UIControlStateDisabled];
        }else{
            descLabel.text = STR(@"默认模式");
            btn3 = btn;
            [btn setImage:IMG(@"right_bottom.png") forState:UIControlStateNormal];
            [btn setImage:IMG(@"right_bottom_un.png") forState:UIControlStateDisabled];
        }
        btn.tag = i;
        [btn setBackgroundImage:IMG(@"TabBarBtn.png") forState:UIControlStateNormal];
        [btn setBackgroundImage:IMG(@"TabBarBtn_selected.png") forState:UIControlStateDisabled];
        [btn addTarget:self action:@selector(buttombBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
    }
	// Do any additional setup after loading the view.
}
-(void)buttombBtnPressed:(UIButton*)btn{
    btn1.enabled = YES; btn2.enabled = YES; btn3.enabled = YES;
    leftView.hidden = YES; midView.hidden = YES; rightView.hidden = YES;
    
    btn12.enabled = YES;
    leftMidView.hidden = YES;
    
    if (btn.tag == 0) {
        
        [self sendDataToBluetooth:nil];
        
        self.title = STR(@"治疗设置");
        btn1.enabled = NO;
        leftView.hidden = NO;
        
    }else if (btn.tag == 1){
        
        [self readBluetoothData:nil];
        
//        UIView *downView = [leftMidView viewWithTag:100];
//        downView.hidden = NO;
//        
//        self.title = STR(@"添加药物");
//        btn12.enabled = NO;
//        leftMidView.hidden = NO;
        
    }else if (btn.tag == 2){
        
        self.title = STR(@"使用记录查询");
        btn2.enabled = NO;
        midView.hidden = NO;
        if (isSelectDrug) {
            [self selectDateWithKey:REC_DRUG_INFO];
        }else{
            [self selectDateWithKey:RECINFO];
        }
    }else{
        
        self.title = STR(@"默认模式");
        btn3.enabled = NO;
        rightView.hidden = NO;

    }
}
-(void)selectDateWithKey:(NSString*)key{
    [savaArray removeAllObjects];
    [timeArray removeAllObjects];
    [curArray removeAllObjects];
    
    NSString *path = [RecInfo storePathWithFileName:key];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSMutableDictionary *timeDic = [[NSMutableDictionary alloc] init];
        NSArray *array =  [RecInfo unarchiverObjectFromPath:path key:key];
        [savaArray addObjectsFromArray:array];
        for (RecInfo *recInfo in array) {
            if (recInfo.day) {
                if (![timeDic objectForKey:recInfo.day]) {
                    [timeArray addObject:recInfo];
                }
            }
            [timeDic setObject:recInfo forKey:recInfo.day];
        }
        
        timeArray = (NSMutableArray *)[[timeArray reverseObjectEnumerator] allObjects];//存的日期
        
        //选择今天的记录
        if (timeArray.count > 0) {
            RecInfo *recInfo = [timeArray objectAtIndex:0];
            [self setCurRecInfo:recInfo];
        }
    }
    [TableView1 reloadData];
    [TableView2 reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (TableView1 == tableView) {
        return curArray.count;
    }
    else{
        return timeArray.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (TableView1 == tableView) {
        return 64;
    }
    else{
        return 35;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (TableView1 == tableView) {
        static NSString *CellIdentifier = @"TableView1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
        //    bg.backgroundColor = [UIColor whiteColor];
        [cell addSubview:bg];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    else{
        static NSString *CellIdentifier = @"TableView2Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 34)];
        bg.backgroundColor = [UIColor whiteColor];
        [cell addSubview:bg];

        GoodLabel *lalelTime2 = [GoodLabel labelWithFont:17 title:STR(@"223432")];
        lalelTime2.textAlignment = UITextAlignmentCenter;
        lalelTime2.textColor = RGB(168, 168, 168, 1);
        lalelTime2.frame = CGRectMake(0, 0, 140, FH(bg));
        [cell addSubview:lalelTime2];
        if (indexPath.row < timeArray.count) {
            RecInfo *recInfo = [timeArray objectAtIndex:indexPath.row];
            lalelTime2.text = recInfo.day;
        }
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
}
-(void)setCurRecInfo:(RecInfo *)recInfo{
    [curArray removeAllObjects];
    for (RecInfo *recInfo1 in savaArray) {
        if ([recInfo1.day isEqualToString:recInfo.day]) {
            [curArray addObject:recInfo1];
        }
    }
    TableView2.hidden = YES;
    [TableView1 reloadData];
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath :(NSIndexPath *)indexPath{
    if (indexPath.row < timeArray.count) {
        RecInfo *recInfo = [timeArray objectAtIndex:indexPath.row];
        [self setCurRecInfo:recInfo];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end




